package com.netintech.common.utils.hk;

import com.alibaba.fastjson.JSONObject;
import com.netintech.common.utils.JsonUtil;
import com.netintech.common.utils.hk.bean.Data;
import com.netintech.common.utils.hk.bean.auth.AddAuthBo;
import com.netintech.common.utils.hk.bean.auth.AddAuthVo;
import com.netintech.common.utils.hk.bean.auth.PersonData;
import com.netintech.common.utils.hk.bean.auth.ResourceInfo;
import com.netintech.common.utils.hk.bean.card.*;
import com.netintech.common.utils.hk.bean.resource.*;
import com.netintech.common.utils.hk.bean.resource.CareData;
import com.netintech.common.utils.hk.bean.task.*;
import com.netintech.common.utils.hk.bean.user.AddUserBo;
import com.netintech.common.utils.hk.bean.user.AddUserVo;
import com.netintech.common.utils.hk.bean.user.DeleteUserBo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author: zhushanshuo
 * @Date: 2020/07/17 15:17
 */
@Component
public class HkThirdService2 {
	
	private static String careDoorUrl = "/api/resource/v2/door/search";
	
	private static String careResourceUrl = "/api/irds/v2/resource/resourcesByParams";
	
	private static String startTaskUrl = "/api/acps/v1/authDownload/task/start";

	private static String addTaskDataUrl = "/api/acps/v1/download/configuration/data/add";

	private static String addTaskUrl = "/api/acps/v1/download/configuration/task/add";
	
	private static String addAuthUrl = "/api/acps/v1/auth_config/add";
	
	private static String orgListUrl = "/api/resource/v1/org/orgList";  // org组织列表
	
	private static String addUserUrl = "/api/resource/v1/person/single/add";  // 添加人员  8c043608c8684c948b23252ad9a4bca2
	
	private static String deleteUserUrl = "/api/resource/v1/person/batch/delete";  // 删除人员
	
	private static String batchCardUrl = "/api/cis/v1/card/bindings";  // 批量开卡
	
	private static String deleteCardUrl = "/api/cis/v1/card/deletion"; // 退卡
	
	private static String careCardUrl = "/api/acs/v2/door/events";  // 出入记录
	
	public static String batchCardJsonString = JsonUtil.toJson(new BatchCardBo());   // 批量开卡参数
	
	public static String deleteCardJsonString = JsonUtil.toJson(new DeleteCardBo());   // 退卡参数
	
	public static String careCardJsonString = JsonUtil.toJson(new CareCardBo());   // 查看卡片出入记录参数
	
	private static String https = "https";
	
	@Autowired
	private ApiUtils apiUtils;
	
	@Autowired
	private EventCreate eventCreate;
	
	@Autowired
	private HkPersonCreate hkPersonCreate;
	
//	@Autowired
//	private HkPersonDao hkPersonDao;
	
	
	
	
//	public static void main(String[] args) throws Exception {
//		Object response = query(url, jsonString);
//		System.out.println(JsonUtil.toJson(response));
//	}
	
	
	public CareDoorVo careDoor(CareDoorBo bo) throws Exception {
		CareDoorVo response = new CareDoorVo();
    	try {
    		CareData data = null;
			Object str = query(careDoorUrl, JsonUtil.toJson(bo));
			data = JsonUtil.fromJson(JsonUtil.toJson(str), CareData.class);
			List<Resource> doorList = data.getData().getList();
			List<ResourceInfo> resourceInfos = new ArrayList<>();
			for (Resource door : doorList) {
				ResourceInfo info = new ResourceInfo();
				info.setResourceIndexCode(door.getIndexCode());
				resourceInfos.add(info);
			}
			response.setResourceInfos(resourceInfos);
		} catch (Exception e) {
			e.printStackTrace();
			// throw new AabException(ExceptionCode.HK接口查询门禁失败);
		}
    	return response;
    }
	
	
	public Data careResource(CareResourceBo bo) throws Exception {
		Data response = null;
    	try {
			Object str = query(careResourceUrl, JsonUtil.toJson(bo));
			response = JsonUtil.fromJson(JsonUtil.toJson(str), Data.class);
		} catch (Exception e) {
			e.printStackTrace();
			// throw new AabException(ExceptionCode.HK接口查询门禁失败);
		}
    	return response;
    }
	
	public Data startTask(StartTaskBo bo) throws Exception {
		Data response = null;
		try {
			Object str = query(startTaskUrl, JsonUtil.toJson(bo));
			response = JsonUtil.fromJson(JsonUtil.toJson(str), Data.class);
		} catch (Exception e) {
			e.printStackTrace();
			// throw new AabException(ExceptionCode.HK接口开始任务失败);
		}
		return response;
	}
	
	public Data addTaskData(AddTaskDataBo bo) throws Exception {
		Data response = null;
		try {
			Object str = query(addTaskDataUrl, JsonUtil.toJson(bo));
			response = JsonUtil.fromJson(JsonUtil.toJson(str), Data.class);
		} catch (Exception e) {
			e.printStackTrace();
			// throw new AabException(ExceptionCode.HK接口添加任务通道失败);
		}
		return response;
	}
	
	public AddTaskVo addTask(AddTaskBo bo) throws Exception {
		AddTaskVo response = new AddTaskVo();
		try {
			TaskData data = null;
			Object str = query(addTaskUrl, JsonUtil.toJson(bo));
			data = JsonUtil.fromJson(JsonUtil.toJson(str), TaskData.class);
			
			if (!"0".equals(data.getCode())) {
				// throw new AabException(ExceptionCode.HK接口添加任务失败);
			}
			
			String taskId = data.getData().getTaskId();
			response.setTaskId(taskId);
		} catch (Exception e) {
			e.printStackTrace();
			// throw new AabException(ExceptionCode.HK接口添加任务失败);
		}
		return response;
	}
	
	public AddAuthVo addAuth(AddAuthBo bo) throws Exception {
		AddAuthVo response = new AddAuthVo();
		try {
			TaskData data = null;
			Object str = query(addAuthUrl, JsonUtil.toJson(bo));
			data = JsonUtil.fromJson(JsonUtil.toJson(str), TaskData.class);
			
			if (!"0".equals(data.getCode())) {
				// throw new AabException(ExceptionCode.HK接口添加权限失败);
			}
			
			String taskId = data.getData().getTaskId();
			response.setTaskId(taskId);
			
		} catch (Exception e) {
			e.printStackTrace();
			// throw new AabException(ExceptionCode.HK接口添加权限失败);
		}
		return response;
	}
	
	public Data orgList(CareCardBo bo) throws Exception {
		Data response = null;
    	try {
			Object str = query(orgListUrl, JsonUtil.toJson(bo));
			response = JsonUtil.fromJson(JsonUtil.toJson(str), Data.class);
		} catch (Exception e) {
			e.printStackTrace();
			// throw new AabException(ExceptionCode.HK接口查询组织失败);
		}
    	return response;
    }
	
	public AddUserVo addUser(AddUserBo bo) throws Exception {
		AddUserVo response = new AddUserVo();
    	try {
    		Data data = null;
    		// 1、添加人员
			Object str = query(addUserUrl, JsonUtil.toJson(bo));
			data = JsonUtil.fromJson(JsonUtil.toJson(str), Data.class);
			
			if (!"0".equals(data.getCode())) {
				// throw new AabException(ExceptionCode.HK接口添加用户失败2, String.valueOf(data.getMsg()));
			}
			String personId = data.getData() + "";
			response.setPersonId(personId);
			
			BatchCardBo batchCardBo = new BatchCardBo();
			batchCardBo.setStartDate(bo.getStartDate());
			batchCardBo.setEndDate(bo.getEndDate());
			List<CardBo> cardList = new ArrayList<>();
			CardBo cardBo = new CardBo();
			cardBo.setCardNo(bo.getPersonName());
			cardBo.setOrgIndexCode(bo.getOrgIndexCode());
			cardBo.setPersonId(data.getData() + "");
			cardList.add(cardBo);
			batchCardBo.setCardList(cardList);
			
			// 2、给人员开卡
			BatchData batchData = batchCard(batchCardBo);
			if (!"0".equals(batchData.getCode())) {
				DeleteUserBo deleteUserBo = new DeleteUserBo();
				deleteUserBo.setPersonIds(Arrays.asList(personId));
				deleteUser(deleteUserBo);
				// throw new AabException(ExceptionCode.HK接口添加用户失败2, String.valueOf(batchData.getMsg()));
			}
			
			HkPerson record = new HkPerson();
			record.setCertificateNo(bo.getCertificateNo());
			record.setCertificateType(bo.getCertificateType());
			record.setOrgIndexCode(bo.getOrgIndexCode());
			record.setPersonId(data.getData() + "");
			record.setPersonName(bo.getPersonName());
			record.setCreateTime(new Date());
			record.setStartDate(bo.getStartDate());
			record.setEndDate(bo.getEndDate());
			hkPersonCreate.process(record);
			
			personId = response.getPersonId();
			
			// 3、添加权限
			String startTime = bo.getStartDate() + "T" + "00:00:00.000" + "+08:00";
			String endTime = bo.getEndDate() + "T" + "23:59:59.999" + "+08:00";
			AddAuthBo authBo = new AddAuthBo();
			List<PersonData> personDatas = new ArrayList<PersonData>();
			PersonData personData = new PersonData();
			personData.setIndexCodes(Arrays.asList(personId));
			personDatas.add(personData);
			authBo.setPersonDatas(personDatas);
			authBo.setStartTime(startTime);
			authBo.setEndTime(endTime);
			CareDoorBo careDoorBo = new CareDoorBo();
			List<ResourceInfo> resourceInfos = careDoor(careDoorBo).getResourceInfos();
			authBo.setResourceInfos(resourceInfos);
			AddAuthVo addAuthVo = addAuth(authBo);
			String authTaskId = addAuthVo.getTaskId();
			
			// 4、添加下载任务
			AddTaskBo addTaskBo = new AddTaskBo();
			AddTaskVo addTaskVo = addTask(addTaskBo);
			String taskId = addTaskVo.getTaskId();
			
			// 5、添加待下载任务通道  auth
			AddTaskDataBo addTaskDataBo = new AddTaskDataBo();
			addTaskDataBo.setTaskId(authTaskId);
			addTaskDataBo.setResourceInfos(resourceInfos);
			Data addTaskData = addTaskData(addTaskDataBo);
			System.out.println("待下载 auth:" + JsonUtil.toJson(addTaskData));
			
			// 6、添加待下载任务通道  task
			addTaskDataBo = new AddTaskDataBo();
			addTaskDataBo.setTaskId(taskId);
			addTaskDataBo.setResourceInfos(resourceInfos);
			addTaskData = addTaskData(addTaskDataBo);
			System.out.println("待下载 task:" + JsonUtil.toJson(addTaskData));
			
			// 7、开始下载任务  auth
			StartTaskBo startTaskBo = new StartTaskBo();
			startTaskBo.setTaskId(authTaskId);
			Data startTaskData = startTask(startTaskBo);
			System.out.println("开始任务 auth:" + JsonUtil.toJson(startTaskData));
			
			// 8、开始下载任务  task
			startTaskBo = new StartTaskBo();
			startTaskBo.setTaskId(taskId);
			startTaskData = startTask(startTaskBo);
			System.out.println("开始任务 task:" + JsonUtil.toJson(startTaskData));
			
			CardData cardData = batchData.getData().get(0);
			String cardId = cardData.getCardId();
			String cardNo = cardData.getCardNo();
			personId = cardData.getPersonId();
			response.setCardId(cardId);
			response.setCardNo(cardNo);
			response.setPersonId(personId);
		} catch (Exception e) {
			e.printStackTrace();
			// throw new AabException(ExceptionCode.HK接口添加用户失败);
		}
    	return response;
    }
	
	
	@SuppressWarnings("unused")
	public Data deleteUser(DeleteUserBo bo) throws Exception {
		Data response = null;
		try {
			Object str = query(deleteUserUrl, JsonUtil.toJson(bo));
			response = JsonUtil.fromJson(JsonUtil.toJson(str), Data.class);
			for (String personId : bo.getPersonIds()) {
				// hkPersonDao.deleteByPrimaryKey(personId);
			}
		} catch (Exception e) {
			e.printStackTrace();
			// throw new AabException(ExceptionCode.HK接口删除用户失败);
		}
		return response;
	}
	
	
	
	public Object careCard(String careCardJsonString) throws Exception {
    	Object response = null;
    	try {
			response = query(careCardUrl, careCardJsonString);
			eventCreate.process(JsonUtil.toJson(response));
		} catch (Exception e) {
			e.printStackTrace();
			if (e instanceof DuplicateKeyException) {
				
			} else {
				// throw new AabException(ExceptionCode.HK接口查询出入记录失败);
			}
		}
    	return response;
    }
	
	//电子通行证销卡
	public Data deleteCard(DeleteCardBo bo) throws Exception {
		Data response = null;
    	try {
			Object str = query(deleteCardUrl, JsonUtil.toJson(bo));
			response = JsonUtil.fromJson(JsonUtil.toJson(str), Data.class);
		} catch (Exception e) {
			e.printStackTrace();
			// throw new AabException(ExceptionCode.HK接口退卡失败);
		}
    	return response;
    }
    
    //电子通行证开卡
    public BatchData batchCard(BatchCardBo bo) throws Exception {
    	BatchData response = null;
    	try {
			Object str = query(batchCardUrl, JsonUtil.toJson(bo));
			response = JsonUtil.fromJson(JsonUtil.toJson(str), BatchData.class);
		} catch (Exception e) {
			e.printStackTrace();
			// throw new AabException(ExceptionCode.HK接口开卡失败);
		}
    	return response;
    }
    
    public Data deleteCard(String deleteCardJsonString) throws Exception {
    	Data response = null;
    	try {
    		Object str = query(deleteCardUrl, deleteCardJsonString);
    		response = JsonUtil.fromJson(JsonUtil.toJson(str), Data.class);
    	} catch (Exception e) {
    		e.printStackTrace();
    		// throw new AabException(ExceptionCode.HK接口退卡失败);
    	}
    	return response;
    }
    
    
    public BatchData batchCard(String batchCardJsonString) throws Exception {
    	BatchData response = null;
    	try {
    		Object str = query(batchCardUrl, batchCardJsonString);
    		response = JsonUtil.fromJson(JsonUtil.toJson(str), BatchData.class);
    	} catch (Exception e) {
    		e.printStackTrace();
    		// throw new AabException(ExceptionCode.HK接口开卡失败);
    	}
    	return response;
    }
    
    private Object query(String url, String jsonString) throws Exception {
        JSONObject parseObject = null;
		try {
			parseObject = JSONObject.parseObject(jsonString.trim());
		} catch (Exception e) {
			// throw new AabException(ExceptionCode.HK接口参数错误);
		}
		String jsonDataByApi = apiUtils.getJSONDataByApi(parseObject, url, https);
		JSONObject dataResult = null;
		try {
			dataResult = JSONObject.parseObject(jsonDataByApi);
			if (dataResult == null) {
				// throw new AabException(ExceptionCode.HK接口返回错误);
			}
			return dataResult;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
    }
    
}

